Expand description
Serialize and deserialize const generic or arbitrarily-large arrays with Serde.
Out of the box, Serde supports a lot of types, but
unfortunately lacks support for arrays that use const generics. This library provides a module
that, in combination with Serde’s with
attribute,
adds that support.
§Example usage
use serde::{Serialize, Deserialize};
use serde_json;
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
struct GenericArray<const N: usize> {
#[serde(with = "serde_arrays")]
arr: [u32; N],
}
let data = GenericArray{ arr: [1; 16] };
let json = serde_json::to_string(&data)?;
let de_data = serde_json::from_str(&json)?;
assert_eq!(data, de_data);
As an added bonus, this also adds support for arbitrarily large arrays beyond the 32 elements that Serde supports:
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
struct LargeArray {
#[serde(with = "serde_arrays")]
arr: [u32; 64],
}
Tuple structs are supported just as easily:
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
struct TupleStruct<const N: usize>(
#[serde(with = "serde_arrays")]
[u32; N],
);
§MSRV
This library relies on the const generics feature introduced in Rust 1.51.0.
§Relevant links
- The Serde issue for const generics support
- serde-big-array is a similar crate, but it
depends on
unsafe
code (whether its use of such is safe or not is beyond this scope)
Functions§
- Deserialize const generic or arbitrarily-large arrays
- Serialize const generic or arbitrarily-large arrays